package com.pur.zsms.common.web;

import java.util.Date;
import java.util.Locale;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.support.RequestContextUtils;

import com.pur.zsms.common.beans.DatePropertyEditorSupport;
import com.pur.zsms.common.exception.Exceptional;
/**
 * web层所有Controller的基类，封装了统一异常处理和获取国际化消息
 */
public class BaseWebController {
	private static Log log = LogFactory.getLog(BaseWebController.class);
	
	public String getMessage(ServletRequest request,String key,Object[] args,Locale locale,String defaultValue){
		WebApplicationContext context = RequestContextUtils.getWebApplicationContext(request);
		return context.getMessage(key, args, defaultValue, locale);
	}
	
	public String getMessage(ServletRequest request,String key,Object[] args,Locale locale){
		WebApplicationContext context = RequestContextUtils.getWebApplicationContext(request);
		return context.getMessage(key, args, locale);
	}
	
	/*public User getSessionUser(HttpSession session){
		Object obj = session.getAttribute("user");
		if(obj == null)return null ;
		return ((User)obj);
	}
	
	public String getSessionUserId(HttpSession session){
		Object obj = getSessionUser(session);
		if(obj == null)return null ;
		return ""+((User)obj).getId();
	}*/
	
	@ExceptionHandler
	public ModelAndView handleException(Exception e,HttpServletRequest request,Locale locale){
		if(log.isDebugEnabled()){
			log.debug(e);
		}
		e.printStackTrace();
		WebApplicationContext context = RequestContextUtils.getWebApplicationContext(request);
		String message = "" ;
		if(e instanceof Exceptional){
			Exceptional exceptional = (Exceptional)e ;
			message = context.getMessage(exceptional.getMessageKey(),(Object[])exceptional.getMessageArgs(),locale);
		}
		java.util.Map<String,Object> map = new java.util.HashMap<String,Object>();
		map.put("failure", true);
		map.put("message", message);
		return new ModelAndView("base/error",map) ;
	}
	
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(Date.class, new DatePropertyEditorSupport());
	}
}
